"""智能剪切板主程序"""

import sys
import signal
from pathlib import Path
from PySide6.QtWidgets import QApplication, QMessageBox
from PySide6.QtCore import QTimer, Qt
from PySide6.QtGui import QIcon

from .database import ClipboardDatabase
from .clipboard_monitor import ClipboardMonitor
from .main_window import MainWindow
from .system_tray import SystemTray


class SmartClipboardApp:
    """智能剪切板应用程序"""
    
    def __init__(self):
        self.app = None
        self.database = None
        self.monitor = None
        self.main_window = None
        self.system_tray = None
        
    def initialize(self):
        """初始化应用程序"""
        # 创建QApplication
        self.app = QApplication(sys.argv)
        self.app.setQuitOnLastWindowClosed(False)  # 关闭窗口时不退出应用
        
        # 设置应用程序属性
        self.app.setApplicationName("智能剪切板")
        self.app.setApplicationVersion("1.0.0")
        self.app.setOrganizationName("Smart Clipboard Team")
        
        # 检查系统托盘支持
        if not self.check_system_tray():
            QMessageBox.critical(None, "错误", "系统不支持托盘图标，程序无法运行。")
            return False
        
        # 初始化数据库
        try:
            self.database = ClipboardDatabase()
            print("数据库初始化完成")
        except Exception as e:
            QMessageBox.critical(None, "数据库错误", f"数据库初始化失败: {str(e)}")
            return False
        
        # 初始化剪切板监控器
        try:
            self.monitor = ClipboardMonitor(self.database)
            print("剪切板监控器初始化完成")
        except Exception as e:
            QMessageBox.critical(None, "监控器错误", f"剪切板监控器初始化失败: {str(e)}")
            return False
        
        # 初始化主窗口
        try:
            self.main_window = MainWindow(self.database, self.monitor)
            print("主窗口初始化完成")
        except Exception as e:
            QMessageBox.critical(None, "窗口错误", f"主窗口初始化失败: {str(e)}")
            return False
        
        # 初始化系统托盘
        try:
            self.system_tray = SystemTray(self.database)
            print("系统托盘初始化完成")
        except Exception as e:
            QMessageBox.critical(None, "托盘错误", f"系统托盘初始化失败: {str(e)}")
            return False
        
        # 设置信号连接
        self.setup_connections()
        
        return True
    
    def check_system_tray(self) -> bool:
        """检查系统托盘支持"""
        from PySide6.QtWidgets import QSystemTrayIcon
        return QSystemTrayIcon.isSystemTrayAvailable()
    
    def setup_connections(self):
        """设置信号连接"""
        # 主窗口信号
        self.main_window.hide_to_tray.connect(self.on_hide_to_tray)
        self.main_window.toggle_topmost.connect(self.on_toggle_topmost)  # 新增主窗口置顶信号连接
        
        # 系统托盘信号
        self.system_tray.show_window.connect(self.on_show_window)
        self.system_tray.quit_application.connect(self.quit_application)
        # 移除系统托盘的置顶信号连接
        
        # 应用程序信号
        self.app.aboutToQuit.connect(self.on_about_to_quit)
    
    def run(self):
        """运行应用程序"""
        if not self.initialize():
            return 1
        
        # 显示主窗口
        self.main_window.show()
        
        # 显示系统托盘
        self.system_tray.show()
        
        # 启动剪切板监控
        self.monitor.start_monitoring()
        
        # 显示启动通知
        self.system_tray.show_message(
            "智能剪切板", 
            "程序已启动，正在监控剪切板变化...",
            timeout=2000
        )
        
        print("智能剪切板启动完成")
        
        # 设置信号处理器
        signal.signal(signal.SIGINT, self.signal_handler)
        signal.signal(signal.SIGTERM, self.signal_handler)
        
        # 运行事件循环
        try:
            return self.app.exec()
        except KeyboardInterrupt:
            print("\n收到中断信号，正在退出...")
            self.quit_application()
            return 0
    
    def signal_handler(self, signum, frame):
        """信号处理器"""
        print(f"\n收到信号 {signum}，正在退出...")
        self.quit_application()
    
    def on_hide_to_tray(self):
        """隐藏到托盘处理"""
        self.main_window.hide()
        self.system_tray.show_message(
            "智能剪切板", 
            "程序已最小化到托盘，双击托盘图标可以重新显示窗口",
            timeout=2000
        )
    
    def on_show_window(self):
        """显示窗口处理"""
        self.main_window.show()
        self.main_window.raise_()
        self.main_window.activateWindow()
    
    def on_toggle_topmost(self):
        """切换窗口置顶状态"""
        # 主窗口已经处理了置顶逻辑，这里只需要同步状态
        pass
    
    def quit_application(self):
        """退出应用程序"""
        print("正在退出应用程序...")
        
        # 停止剪切板监控
        if self.monitor:
            self.monitor.stop_monitoring()
        
        # 隐藏系统托盘
        if self.system_tray:
            self.system_tray.hide()
        
        # 关闭主窗口
        if self.main_window:
            self.main_window.close()
        
        # 退出应用程序
        if self.app:
            self.app.quit()
    
    def on_about_to_quit(self):
        """应用程序即将退出"""
        print("应用程序即将退出，清理资源...")
        
        # 停止监控
        if self.monitor:
            self.monitor.stop_monitoring()
        
        # 清理旧数据（保留最新100条）
        if self.database:
            try:
                self.database.clear_old_items(100)
                print("数据库清理完成")
            except Exception as e:
                print(f"数据库清理失败: {e}")


def main():
    """主函数"""
    # 设置高DPI支持
    QApplication.setHighDpiScaleFactorRoundingPolicy(Qt.HighDpiScaleFactorRoundingPolicy.PassThrough)
    
    # 创建并运行应用程序
    app = SmartClipboardApp()
    return app.run()


if __name__ == "__main__":
    sys.exit(main())
